import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class {{ function_name  }}(BaseTaxPolicySpider):
    name = "{{ name }}"

    province: str = "{{ province }}"  # 取表格
    city: str = "{{ city }}"  # 取表格
    county: str = "{{ county }}"  # 取表格
    park: str = "{{ park }}"  # 取表格
    source: str = "{{ source }}"  # 取表格 同一个来源合并
    url: str = "{{ url }}"  # 注明入口网址，以便后续排错
    headers = {
        'Content-Type': 'application/json'
    }
    host = url.split('.gov.cn')[0] + '.gov.cn'

    def start_requests(self):
        self.site_code = self.url.split('.')[0].split('/')[-1]
        yield scrapy.Request(self.url, callback=self.parse_content)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        if 'stlPageContentsElement' in response.text:
            siteId = response.xpath('//script').re_first("siteId: (.*),")
            pageChannelId = response.xpath('//script').re_first("pageChannelId: (.*),")
            templateId = response.xpath('//script').re_first("templateId: (.*),")
            totalNum = response.xpath('//script').re_first("totalNum: (.*),")
            pageCount = response.xpath('//script').re_first("pageCount: (.*),")
            currentPageIndex = response.xpath('//script').re_first("currentPageIndex: (.*),")
            stlPageContentsElement = response.xpath('//script').re_first("stlPageContentsElement: '(.*)'")
            url = f"{self.host}/api/stl/actions/pagecontents"
            data = {
                "siteId": int(siteId),
                "pageChannelId": int(pageChannelId),
                "templateId": int(templateId),
                "totalNum": int(totalNum),
                "pageCount": int(pageCount),
                "currentPageIndex": int(currentPageIndex),
                "stlPageContentsElement": stlPageContentsElement
            }
            data = json.dumps(data, separators=(',', ':'))
            yield scrapy.Request(url, body=data, callback=self.parse_list, headers=self.headers, dont_filter=True, method='POST', meta=meta)
        else:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True, meta=meta)

    def parse_list(self, response, **kwargs):
        print()
        prev_item = response.meta.get('item')
        try:
            elem_list = response.xpath("//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=5]")
        except:
            elem_list = scrapy.Selector(text=response.json()['html']).xpath("//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=5]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            if f'/-{self.site_code}/' in item['source_url']:
                item['source_url'] = item['source_url'].replace('/-4663/', '/4663/')
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            print(response.url, item['source_url'])
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下一页' in response.text:
                total_page = response.xpath(""".""").re_first(r"""共\s*(\d+)\s*页""")
                print("total_page", total_page)
                for page_num in range(1, int(int(total_page) / 1 + 2)):
                    url = response.url.replace('.html', f'_{page_num}.html')
                    yield response.follow(url, callback=self.parse_content, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl {{ name }}".split())

